import React, { lazy, Suspense } from 'react';
import { BrowserRouter, HashRouter, Router, Route, Switch } from 'dva/router';
import { checkLogin } from './services/user';
// 启用路由配置
import { renderRoutes } from 'react-router-config';
// 导入Loading加载组件
import Loading from './components/Loading';
// 导入组件
import App from './App';
// import CountPage from './routes/CountPage';
// import UserPage from './routes/UserPage';
// import MessagePage from './routes/MessagePage';
// **正常的模块导入必须放在懒加载之前
// const MessagePage = lazy(() => slowImport(import('./routes/MessagePage'),2000));
// const MessagePage=lazy(()=>import('./routes/MessagePage'));
// 路由懒加载; 路由/组件懒加载都必须使用Suspense组件包裹
const routes = [
  {
    path: '/login',
    exact: true,
    component: lazy(() => import('./routes/LoginPage'))
  },
  {
    path: '/',
    exact: false,  // 切记:父级路由一定要使用模糊匹配
    component: App,
    routes: [
      {
        path: '/message',
        exact: true,
        component: lazy(() => import('./routes/MessagePage'))
      },
      {
        path: '/count',
        exact: true,
        component: lazy(() => import('./routes/CountPage'))
      },
      {
        path: '/users',
        exact: true,
        component: lazy(() => import('./routes/UserPage'))
      },
      {
        path: '/flinks',
        exact: true,
        component: lazy(() => import('./routes/FlinkPage'))
      },
      {
        path:'/articles',
        exact:true,
        component:lazy(()=>import('./routes/ArticlePage'))
      },
      {
        path:'/article/:id',
        exact:true,
        component:lazy(()=>import('./routes/ArticleEditPage'))
      }
    ]
  }
];

function RouterConfig({ history }) {
  history.listen(()=>{
    // 检测登录
    if(!checkLogin()&&history.location.pathname!=='/login'){
      const {pathname}=history.location;
      history.push({pathname:'/login',state:{from:pathname}});
    }else{
      if(history.location.pathname==='/') history.push('/users');
    }
    
  });
  return (
    <Router history={history}>

      <Switch>
        {/* 嵌套路由的父级路由一定要使用模糊匹配 */}
        <Suspense fallback={<Loading />}>
          {renderRoutes(routes)}
        </Suspense>
      </Switch>
    </Router>
  );
}


// 为了看到异步加载组件的效果, 实现的一个延时加载的方法
function slowImport(value, ms = 1000) {
  return new Promise(resolve => {
    setTimeout(() => resolve(value), ms);
  })
}


export default RouterConfig;
